from socket import *

class UDPClient:
    def __init__(self,ip,port):
        self.client_socket = socket(AF_INET, SOCK_DGRAM)
        self.ip=ip
        self.port=port

    def __send_message(self,action,username,message):
        data=f"{action} {username} {message}"
        self.client_socket.sendto(data.encode("utf-8"),(self.ip,self.port))

    def __receive_message(self):
        data,address=self.client_socket.recvfrom(1024)
        if data.decode("utf-8")=="chart":
            return
        print(data.decode('utf-8'))


    def main(self,action,username,message=""):
        self.__send_message(action,username,message)
        self.__receive_message()


if __name__ == '__main__':
    udp = UDPClient('127.0.0.1',2222)
    name=input("欢迎来到天天聊天平台,请输入您的姓名:")
    name="".join(name.split())
    udp.main("L",name)
    while True:
        try:
            message=input("input message press q to quit:")
            if message == "Q":
                udp.main("Q", name)
                break
        except:
            udp.main("Q", name)
            break
        else:
            udp.main("C", name, message)
